package 栈;

import java.util.Iterator;

public class LinkedListStack<E> implements Stack<E> ,Iterable<E>{
   //利用链表实现栈

    static class Node<E>{//利用链表实现
        E value;
        Node<E> next;
        public Node(E value,Node<E> next){
            this.value=value;
            this.next=next;
        }
    }
    private int capacity;
    private int size;
    private Node<E> head=new Node<>(null,null);
    public LinkedListStack(int capacity){
        this.capacity=capacity;
    }
    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            Node<E> p=head.next;
            @Override
            public boolean hasNext() {//判断是否为空
                return p!=null;
            }

            @Override
            public E next() {//向下遍历
               E value=p.value;
               p=p.next;
               return value;
            }
        };
    }

    @Override
    public boolean push(E value) {
       if(isFull()){
           return false;
       }
       head.next=new Node<>(value,head.next);
       size++;
       return true;
    }

    @Override
    public E pop() {
       if(isEmpty()){
           return null;
       }
       Node<E> first=head.next;
       head.next=first.next;//删除该节点
       size--;
       return first.value;
    }

    @Override
    public E peek() {
       if(isEmpty()){
           return null;
       }
       Node<E> first=head.next;
       return first.value;
    }

    @Override
    public boolean isEmpty() {
       return size==0;
    }

    @Override
    public boolean isFull() {
       return size==capacity;
    }

}
